/**
 * Copyright(c) by JNet Smartware Group.
 * All rights reserved. Not distribution or redistribution without
 * any permission of JNet Smartware Group.
 * 
 * @author thuc
 * 2010/03/15
 * Program: SWTMenuEntry.java
 */
package vn.smartware.co.client.admin;

import java.util.ArrayList;
import java.util.Locale;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;

import vn.smartware.co.commons.Const;
import vn.smartware.co.commons.SWTUtils;
import vn.smartware.co.framework.bean.MenuDTO;
import vn.smartware.co.framework.common.BaseConstant;
import vn.smartware.co.framework.exception.FatalException;
import vn.smartware.co.framework.exception.SessionTimeOutException;
import vn.smartware.co.framework.form.BaseForm;
import vn.smartware.co.framework.plugin.LangResources;
import vn.smartware.co.framework.swt.base.JNetComposite;
import vn.smartware.co.framework.utils.MsgBoxUtils;
import vn.smartware.co.java.net.commons.Utils;

/**
 * SWTMenuEntry
 * @author thuctt
 */
public class SWTMenuEntry extends JNetComposite {

	private static Log log = LogFactory.getLog(SWTMenuEntry.class);

	private Button btnClose;

	private Button btnSave;

	private Table tblInfo;

	private Group grp;
	
	private CLabel clblMessage;

	private Button btnDelete;

	private static final int TBL_ROW_COUNT = 12;
	
	/**
	 * Constructor
	 * @param parent
	 * @param form 
	 * @param prgName 
	 */
	public SWTMenuEntry(Composite parent, int style, String prgName) {
		super(parent, style, prgName);
	}

	/**
	 * Clear button click
	 */
	@Override
	protected void clearAction() {
		SWTUtils.OperatorUI.clearAll(this.getChildren());
	}

	/**
	 * get initialize data
	 *
	 */
	protected boolean loadData() throws FatalException {
		BaseForm form = new BaseForm();
		form.setActionForm("baseForm");
		form.setActionMethod("getMenuListWithoutAuth");
		
		form = (BaseForm)execute(form);
		
		if (form.getMenu().isEmpty()){
			MsgBoxUtils.warningMsgBox("warning.NO_DATA_FOUND");
			btnSave.setEnabled(false);
			btnClose.setEnabled(true);
			btnClose.setFocus();
			return false;
		}
		
		displayTableMenuInfo(form.getMenu());
		return true;
	}

	/**
	 * set data to table
	 * @param list
	 */
	private void displayTableMenuInfo(ArrayList<MenuDTO> list) {
		tblInfo.removeAll();
		int rowcount = TBL_ROW_COUNT;
		if (list.size() >= rowcount){
			rowcount = list.size() + 2;
		}
		for (int i = 0; i < rowcount; i++) {
			TableItem tblItem = new TableItem(tblInfo, SWT.NONE);
			if (i < list.size()){
				MenuDTO menu = (MenuDTO)list.get(i);
				String[] items = new String[tblInfo.getColumnCount()];
				int idx = 0;
				items[idx++] = "";
				items[idx++] = Integer.toString(menu.getMenuId());
//				items[idx++] = LangResources.getText(menu.getMenuName());
//				items[idx++] = menu.getEnName();
				String[] supportLangs = LangResources.getSupportLanguage();
				for (String lang : supportLangs) {
					items[idx++] = LangResources.getText(menu.getMenuName());
				}
				
				items[idx++] = menu.getInsertYmd();
				items[idx++] = menu.getDeleteYmd();
				
				tblItem.setText(items);
				tblItem.setData(menu);
				
				if (!Utils.isNullEmpty(menu.getDeleteYmd())){
					tblItem.setForeground(Const.COLOR_DATA_CANCELED);
				}
			}
			
			if (i%2 == 0){
				tblItem.setBackground(BaseConstant.COLOR_TABLE_ROW_EVEN);
			}
		}
		tblInfo.setData(list);
		tblInfo.setSelection(0);
	}

	/**
	 * Create contents of the dialog
	 */
	protected void initialize() {
		grp = new Group(this, SWT.NONE);
		grp.setBounds(15, 10, 695, 310);
		grp.setBackground(BaseConstant.COLOR_BGR_BASE);
		
		tblInfo = new Table(grp, SWT.FULL_SELECTION | SWT.BORDER);
		tblInfo.setBounds(20, 20, 651, 273);
		tblInfo.setFont(BaseConstant.FONT_BASE_LABEL);
		tblInfo.setData(BaseConstant.TABLE_ROW_COUNT, Integer.toString(TBL_ROW_COUNT));
		tblInfo.setLinesVisible(true);
		tblInfo.setHeaderVisible(true);
		
		final TableColumn tcolStatus = new TableColumn(tblInfo, SWT.NONE);
		tcolStatus.setWidth(30);
		
		final TableColumn tcolID = new TableColumn(tblInfo, SWT.NONE);
		tcolID.setAlignment(SWT.RIGHT);
		tcolID.setWidth(40);
		tcolID.setText(LangResources.getText("SWTMenuEntry.tcolID"));
		
//		final TableColumn tcolVnName = new TableColumn(tblInfo, SWT.NONE);
//		tcolVnName.setWidth(180);
//		tcolVnName.setText(LangResources.getText("SWTMenuEntry.tcolVnName"));
//		
//		final TableColumn tcolEnName = new TableColumn(tblInfo, SWT.NONE);
//		tcolEnName.setWidth(180);
//		tcolEnName.setText(LangResources.getText("SWTMenuEntry.tcolEnName"));
		String[] supportLangs = LangResources.getSupportLanguage();
		for (String lang : supportLangs) {
			final TableColumn tcolName = new TableColumn(tblInfo, SWT.NONE);
			tcolName.setWidth(180);
			Locale locale = new Locale(lang);
			tcolName.setText(locale.getDisplayCountry() + " Name");
		}
		
		final TableColumn tcolCreateYmd = new TableColumn(tblInfo, SWT.NONE);
		tcolCreateYmd.setWidth(100);
		tcolCreateYmd.setText(LangResources.getText("SWTMenuEntry.tcolCreateYmd"));
		
		final TableColumn tcolDeleteYmd = new TableColumn(tblInfo, SWT.NONE);
		tcolDeleteYmd.setWidth(100);
		tcolDeleteYmd.setText(LangResources.getText("SWTMenuEntry.tcolDeleteYmd"));
		
		final TableEditor editor = new TableEditor(tblInfo);
	    editor.horizontalAlignment = SWT.LEFT;
	    editor.grabHorizontal = true;
	    
		tblInfo.addMouseListener(new MouseAdapter() {
			public void mouseDoubleClick(final MouseEvent event) {
				Control old = editor.getEditor();
				if (old != null){
					old.dispose();
				}
				Point pt = new Point(event.x, event.y);
				final TableItem item = tblInfo.getItem(pt);
				if (item == null) {
					return;
				}
				//get cell clicked
				int column = -1;
				int n = tblInfo.getColumnCount()-2;
				for (int i = 0; i < n; i++) {
					Rectangle rect = item.getBounds(i);
					if (rect.contains(pt)) {
						column = i;
						break;
					}
				}
				if (column > 1){
					setTextControl(editor, item, column);
				}
			}
			
			public void mouseDown(MouseEvent event) {
				Control old = editor.getEditor();
				if (old != null){
					old.dispose();
				}

				Point pt = new Point(event.x, event.y);

				final TableItem item = tblInfo.getItem(pt);
				if (item != null) {
					tblInfo.showItem(item);
					tblInfo.setSelection(item);
				}
			}
		});
		tblInfo.addKeyListener(new KeyAdapter() {
			public void keyPressed(final KeyEvent e) {
				if (SWTUtils.KeyProcess.getKeyCode(e.keyCode).equals(Const.KEY_CODE_ENTER)) {
					Control old = editor.getEditor();
					if (old != null){
						old.dispose();
					}
					final TableItem item = tblInfo.getItem(tblInfo.getSelectionIndex());
					//get cell clicked
					setTextControl(editor, item, 2);
				}
			}
		});
		
		btnDelete = new Button(this, SWT.NONE);
		btnDelete.addFocusListener(new FocusAdapter() {
			public void focusGained(final FocusEvent arg0) {
				clblMessage.setText("");
			}
		});
		btnDelete.setBounds(398, 330, 100, 23);
		btnDelete.setFont(BaseConstant.FONT_BASE_BUTTON);
		btnDelete.setText(LangResources.getText("btnDelete"));
		btnDelete.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		btnDelete.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				deleteAction();
			}
		});

		btnSave = new Button(this, SWT.NONE);
		btnSave.addFocusListener(new FocusAdapter() {
			public void focusGained(final FocusEvent arg0) {
				clblMessage.setText("");
			}
		});
		btnSave.setBounds(504, 330, 100, 23);
		btnSave.setFont(BaseConstant.FONT_BASE_BUTTON);
		btnSave.setText(LangResources.getText("btnSave"));
		btnSave.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		btnSave.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				saveAction();
			}
		});
		
		btnClose = new Button(this, SWT.NONE);
		btnClose.addFocusListener(new FocusAdapter() {
			public void focusGained(final FocusEvent arg0) {
				clblMessage.setText("");
			}
		});
		btnClose.setBounds(610, 330, 100, 23);
		btnClose.setFont(BaseConstant.FONT_BASE_BUTTON);
		btnClose.setText(LangResources.getText("btnClose"));
		btnClose.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		btnClose.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				if (!closeAction()){
					btnClose.setFocus();
				}
			}
		});
		
		clblMessage = new CLabel(this, SWT.RIGHT | SWT.SHADOW_IN | SWT.BORDER);
		clblMessage.setAlignment(SWT.CENTER);
		clblMessage.setForeground(SWTResourceManager.getColor(0, 0, 255));
		clblMessage.setBounds(15, 329, 250, 25);
		clblMessage.setFont(SWTResourceManager.getFont("Microsoft Sans Serif", 10, SWT.BOLD));
		clblMessage.setBackground(SWTResourceManager.getColor(232, 255, 251));
	}

	/**
	 * set text control editor
	 * @param editor
	 * @param item
	 * @param column
	 */
	private void setTextControl(final TableEditor editor, final TableItem item, final int column) {

		final Text text = new Text(tblInfo, SWT.NONE);
		text.setForeground(item.getForeground());

		text.setText(item.getText(column));
		text.setForeground(item.getForeground());
		text.setBackground(BaseConstant.COLOR_TEXT_REQUIRED);
		text.selectAll();
		text.setFocus();

		editor.minimumWidth = text.getBounds().width;
		editor.setEditor(text, item, column);

		final int col = column;
		text.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent event) {
				item.setText(col, text.getText());
			}
		});
		text.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				// close the text editor and copy the data over
				// when the user hits "ENTER"
				if (SWTUtils.KeyProcess.getKeyCode(e.keyCode).equals(Const.KEY_CODE_ENTER)) {
					item.setText(col, text.getText());

					MenuDTO menu = (MenuDTO)item.getData();
					if (col == 3){//last column
						String colVnName = item.getText(2).trim();
						String colEnName = item.getText(3).trim();
						if (null != menu && menu.getMenuId() != -1){
							if (!menu.getVnName().equals(colVnName)
									|| !menu.getEnName().equals(colEnName)){
								
								item.setText(0, Const.UPDATE_SYMBOL);
								item.setBackground(Const.COLOR_DATA_ROW_CHANGED);
								menu.setVnName(colVnName);
								menu.setEnName(colEnName);
								item.setData(menu);
							}
							
						}else{
							if (!Utils.isNullEmpty(colVnName) || !Utils.isNullEmpty(colEnName)){
								item.setText(0, Const.INSERT_SYMBOL);
								item.setBackground(Const.COLOR_DATA_ROW_CHANGED);
								menu = new MenuDTO();
								menu.setVnName(colVnName);
								menu.setEnName(colEnName);
								item.setData(menu);
							}
						}
					}
					
					text.dispose();
					
					if (col < tblInfo.getColumnCount()-3){
						setTextControl(editor, item, col + 1);
						return;
					}
					
					if (Utils.isNullEmpty(item.getText(2)) && Utils.isNullEmpty(item.getText(3))){
						item.setText(0, "");
						int idx = tblInfo.getSelectionIndex();
						if (idx % 2 == 0){
							item.setBackground(BaseConstant.COLOR_TABLE_ROW_EVEN);
						}else{
							item.setBackground(BaseConstant.COLOR_TEXT_NORMAL);
						}
						return;
					}
					
					int currentRecIndex = tblInfo.getSelectionIndex();
					if (currentRecIndex == tblInfo.getItemCount()-1){// last row
						final TableItem nextItem = new TableItem(tblInfo, SWT.NONE);
						if ((currentRecIndex + 1) % 2 == 0){
							nextItem.setBackground(BaseConstant.COLOR_TABLE_ROW_EVEN);
						}else{
							nextItem.setBackground(BaseConstant.COLOR_TEXT_NORMAL);
						}
					}
					
					final TableItem nextItem = tblInfo.getItem(currentRecIndex + 1);
					if (null != nextItem){
						tblInfo.setSelection(currentRecIndex + 1);
						setTextControl(editor, nextItem, 2);
					}else{
						tblInfo.showSelection();
					}
					return;
				}
			}
		});
		// close the text editor when the user tabs away
		text.addFocusListener(new FocusAdapter() {
			public void focusLost(FocusEvent e) {
				
				item.setText(col, text.getText());
				
				MenuDTO menu = (MenuDTO)item.getData();
				if (null == menu){
					String colVnName = item.getText(2);
					String colEnName = item.getText(3);
					if (!Utils.isNullEmpty(colVnName) || !Utils.isNullEmpty(colEnName)){
						item.setText(0, Const.INSERT_SYMBOL);
						item.setBackground(Const.COLOR_DATA_ROW_CHANGED);
					}
					
				}else{
					if (menu.getMenuId() != -1){
						item.setText(0, Const.UPDATE_SYMBOL);
						item.setBackground(Const.COLOR_DATA_ROW_CHANGED);
					}else{
						item.setText(0, Const.INSERT_SYMBOL);
						item.setBackground(Const.COLOR_DATA_ROW_CHANGED);
					}
				}
				
				text.dispose();
			}
		});
		// ESC pressed
		text.addListener(SWT.Traverse, new Listener() {
			public void handleEvent(Event e) {
				if (e.detail == SWT.TRAVERSE_ESCAPE) {
					e.doit = false;
					
					item.setText(col, text.getText());
					text.dispose();
				}
			}
		});
	}

	/**
	 * saveAction
	 */
	protected void saveAction() {
		log.info("saveAction start.");
		ArrayList<MenuDTO> registLs = new ArrayList<MenuDTO>();
		TableItem[] tblItems = tblInfo.getItems();
		for (int i = 0; i < tblItems.length; i++) {
			String status = tblItems[i].getText(0);
			if (!Utils.isNullEmpty(status)){
				if (status.equals(Const.UPDATE_SYMBOL)){
					MenuDTO menu = (MenuDTO)tblItems[i].getData();
					menu.setVnName(tblItems[i].getText(2));
					menu.setEnName(tblItems[i].getText(3));
					registLs.add(menu);
				}else if (status.equals(Const.INSERT_SYMBOL)){
					MenuDTO menu = new MenuDTO();
					menu.setVnName(tblItems[i].getText(2));
					menu.setEnName(tblItems[i].getText(3));
					registLs.add(menu);
				}
			}
		}
		
		try {
			if (registLs.isEmpty()){
				MsgBoxUtils.warningMsgBox("warning.NO_DATA_SAVE");
				return;
			}
			BaseForm form = new BaseForm();
			form.setActionForm("baseForm");
			form.setActionMethod("registMenu");
			form.setMenu(registLs);
			
			form = (BaseForm)execute(form);
			
			MsgBoxUtils.setStatusLabelMessage(clblMessage, "info.SAVE_SUCCESSFUL");
			
			loadData();
			
		} catch (SessionTimeOutException e) {
			log.error("SessionTimeOutException", e);
		} catch (FatalException e) {
			log.error("FatalException", e);
			fatalErrorMsgBox();
		}
	}

	/**
	 * delete action
	 */
	protected void deleteAction() {
		try {
			log.info("deleteAction start.");
			
			int idx = tblInfo.getSelectionIndex();
			TableItem item = tblInfo.getItem(idx);
			
			if (Utils.isNullEmpty(item.getData())){
				if (Utils.isNullEmpty(item.getText(2))
						&& Utils.isNullEmpty(item.getText(3))){
					
					MsgBoxUtils.errorMsgBox("errors.NOT_SELECTED_RECORD");
					btnDelete.setFocus();
					return;
					
				} else if (Utils.isNullEmpty(item.getText(2))
						|| Utils.isNullEmpty(item.getText(3))) {
					
					tblInfo.remove(idx);
					redrawTable();
					return;
				}
			}
			
			if (SWT.NO == MsgBoxUtils.questionMsgBox("question.BE_SURE")){
				btnDelete.setFocus();
				return;
			}
			
			MenuDTO menu = (MenuDTO)item.getData();
			if (menu.getMenuId() == -1){
				tblInfo.remove(idx);
				redrawTable();
				return;
			}
					
			ArrayList<MenuDTO> registLs = new ArrayList<MenuDTO>();
			registLs.add(menu);
			
			BaseForm form = new BaseForm();
			form.setActionForm("baseForm");
			form.setActionMethod("deleteMenu");
			form.setMenu(registLs);
			
			form = (BaseForm)execute(form);
			
			MsgBoxUtils.setStatusLabelMessage(clblMessage, "info.DELETE_SUCCESSFUL");
			
			loadData();
		}
		catch (SessionTimeOutException e) {
			log.error("SessionTimeOutException", e);
		}
		catch (FatalException e) {
			log.error("FatalException", e);
			fatalErrorMsgBox();
		}
	}

	/**
	 * redraw table
	 *
	 */
	private void redrawTable() {

		int currentRowCount = tblInfo.getItemCount();
		int rowcount = TBL_ROW_COUNT > currentRowCount ? TBL_ROW_COUNT : currentRowCount;
		for (int i = 0; i < rowcount; i++) {
			TableItem tblItem = null;
			if (i >= currentRowCount){
				tblItem = new TableItem(tblInfo, SWT.NONE);
			}else{
				tblItem = tblInfo.getItem(i);
			}
			
			Color color = tblItem.getBackground();
			if (!color.equals(Const.COLOR_DATA_ROW_CHANGED)){
				tblItem.setBackground(BaseConstant.COLOR_TEXT_NORMAL);
				if (i%2 == 0){
					tblItem.setBackground(BaseConstant.COLOR_TABLE_ROW_EVEN);
				}
			}
		}
	}

	/**
	 * lockScreen
	 * @param flg 
	 */
	protected void lockScreen(boolean flg) {
		SWTUtils.OperatorUI.setEnableAll(this.getChildren(), !flg);
	}
}
